import React, { Component } from "react";
import {
  Button,
  DatePicker,
  Input,
  Badge,
  Table,
  Divider,
  Popconfirm,
  message
} from "antd";
import { connect } from "dva";
import moment from "moment";
import { Link } from "dva/router";
import tableFilter from "../../../components/tableFilter";
import styles from "./DataManagement.less";

const { RangePicker } = DatePicker;
const { Search } = Input;

const dataReturn = text => {
  if (text === 1) {
    return "API";
  }
  if (text === 2) {
    return "ADS";
  }
  if (text === 3) {
    return "DataHub";
  }
  return "LogHub";
};

@connect(stores => ({
  dsData: stores.dataSource
}))
@tableFilter
class DataManagement extends Component {
  state = {
    pageSize: 10,
    pageNum: 1,
    ownerDept: [],
    dsType: [],
    useStatus: [],
    ascOrDesc: "desc",
    startTime: "",
    endTime: "",
    inputContent: ""
  };

  componentDidMount() {
    const { dispatch } = this.props;
    const { pageNum, pageSize, ascOrDesc } = this.state;
    dispatch({
      type: "dataSource/getDatasourceList",
      payload: { pageNum, pageSize, ascOrDesc }
    });
    dispatch({
      type: "dataSource/getDepart",
      payload: { pageNum, pageSize: "10000", ascOrDesc }
    });
  }

  dateChange = e => {
    if (e && e.length > 0) {
      this.setState(
        {
          startTime: e[0].format("YYYY-MM-DD"),
          endTime: e[1].format("YYYY-MM-DD"),
          pageNum: 1
        },
        () => {
          this.filterFun();
        }
      );
    } else {
      this.setState(
        {
          startTime: "",
          endTime: "",
          pageNum: 1
        },
        () => {
          this.filterFun();
        }
      );
    }
  };

  handleSearch = e => {
    this.setState(
      {
        inputContent: e,
        pageNum: 1
      },
      () => {
        this.filterFun();
      }
    );
  };

  clearChange = e => {
    if (e.target.value === "") {
      this.setState(
        {
          inputContent: "",
          pageNum: 1
        },
        () => {
          this.filterFun();
        }
      );
    }
  };

  handleTableChange = (e, filters, sorter) => {
    const { current, pageSize } = e;
    const { ownerDept, dsType, useStatus } = this.state;
    this.setState(
      {
        pageNum:
          (filters.ownerDeptName && filters.ownerDeptName !== ownerDept) ||
          (filters.dsType && filters.dsType !== dsType) ||
          (filters.useStatus && filters.useStatus !== useStatus)
            ? 1
            : current,
        pageSize,
        ascOrDesc: sorter.order && sorter.order === "ascend" ? "asc" : "desc",
        ownerDept: filters.ownerDeptName ? filters.ownerDeptName : [],
        dsType: filters.dsType ? filters.dsType : [],
        useStatus: filters.useStatus ? filters.useStatus : []
      },
      () => {
        this.filterFun();
      }
    );
  };

  filterFun = () => {
    const {
      ownerDept,
      dsType,
      useStatus,
      startTime,
      endTime,
      inputContent,
      pageSize,
      ascOrDesc,
      pageNum
    } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: "dataSource/getDatasourceList",
      payload: {
        pageNum,
        pageSize,
        ascOrDesc,
        ownerDept: ownerDept[0],
        useStatus: useStatus[0],
        dsType: dsType[0],
        creTimeStart: startTime === "" ? undefined : startTime,
        creTimeEnd: endTime === "" ? undefined : endTime,
        dsName: inputContent === "" ? undefined : inputContent
      }
    });
    dispatch({
      type: "dataSource/getDepart",
      payload: {
        pageNum,
        pageSize: "10000",
        ascOrDesc,
        ownerDept: ownerDept[0],
        useStatus: useStatus[0],
        dsType: dsType[0],
        creTimeStart: startTime === "" ? undefined : startTime,
        creTimeEnd: endTime === "" ? undefined : endTime,
        dsName: inputContent === "" ? undefined : inputContent
      }
    });
  };

  startconfirm = id => {
    const { dispatch } = this.props;
    dispatch({
      type: "dataSource/delDatasource",
      payload: { dsId: id }
    }).then(() => {
      const { dsData } = this.props;
      const { errCode, errMsg } = dsData;
      if (errCode === 0) {
        message.success("删除成功");
        this.filterFun();
      } else {
        message.error(errMsg);
      }
    });
  };

  render() {
    // const { history } = this.props;
    const { dsData, getColumnSearchProps = () => {} } = this.props;
    const {
      dsList = [],
      totalCount = 0,
      loading = true,
      hasDepart = []
    } = dsData;
    const DepartList = hasDepart.map(item => {
      const temp = { text: item.ownerDeptName, value: item.ownerDept };
      return temp;
    });
    const { pageNum } = this.state;
    const state = { operate: "add" };
    const columns = [
      {
        title: "数据源名称",
        dataIndex: "dsName",
        render: text => (
          <span
            title={text}
            style={{
              maxWidth: 180,
              textOverflow: "ellipsis",
              display: "block",
              whiteSpace: "nowrap",
              overflow: "hidden"
            }}
          >
            {text}
          </span>
        )
      },
      {
        title: "归属部门",
        dataIndex: "ownerDeptName",
        filterMultiple: false,
        filters: DepartList,
        ...getColumnSearchProps(DepartList)
      },
      {
        title: "类型",
        dataIndex: "dsType",
        filterMultiple: false,
        filters: [
          { text: "API", value: 1 },
          { text: "ADS", value: 2 },
          { text: "DataHub", value: 3 },
          { text: "LogHub", value: 4 }
        ],
        render: text => <div>{dataReturn(text)}</div>
      },
      {
        title: "状态",
        filterMultiple: false,
        dataIndex: "useStatus",
        filters: [{ text: "未提交", value: 0 }, { text: "已提交", value: 1 }],
        render: text => (
          <div>
            {text === 1 ? (
              <Badge status="success" text="已提交" />
            ) : (
              <Badge status="default" text="未提交" />
            )}
          </div>
        )
        // width: "20%"
      },
      {
        title: "管理员",
        dataIndex: "owner",
        render: text =>
          JSON.parse(text) && JSON.parse(text).length > 0
            ? JSON.parse(text)[0].name
            : "-"
      },
      {
        title: "创建时间",
        dataIndex: "timeCreate",
        sorter: true,
        defaultSortOrder: "descend",
        render: (text, record) =>
          moment(record.timeCreate).format("YYYY-MM-DD HH:mm:ss")
      },
      {
        title: "操作",
        dataIndex: "operate",
        render: (text, record) => {
          const states = { operate: "mod", dsId: record.dsId };
          const detailState = { operate: "detail", dsId: record.dsId };
          return (
            <span>
              <Link
                to={`/intellPush/recommendCenter/dataSource/dataSourceDetail?key=${JSON.stringify(
                  detailState
                )}`}
              >
                详情
              </Link>
              <Divider type="vertical" />
              <Link
                to={`/intellPush/recommendCenter/dataSource/editInfo?key=${JSON.stringify(
                  states
                )}`}
                disabled={!record.dataPrivilege}
              >
                编辑
              </Link>
              <Divider type="vertical" />
              <Popconfirm
                title={`你是否要删除${record.dsName}?`}
                onConfirm={() => this.startconfirm(record.dsId)}
                onCancel={this.startcancel}
                okText="确定"
                cancelText="取消"
                placement="topRight"
              >
                <a disabled={!record.dataPrivilege || record.inService}>删除</a>
              </Popconfirm>
            </span>
          );
        }
      }
    ];
    return (
      <div className={styles.root}>
        <div className={styles.topSelect}>
          <Link
            to={`/intellPush/recommendCenter/dataSource/addInfo?key=${JSON.stringify(
              state
            )}`}
          >
            <Button type="primary" style={{ fontSize: 14 }}>
              新增
            </Button>
          </Link>
          <div style={{ color: "rgba(0,0,0,0.85)" }}>
            创建时间：
            <RangePicker
              showTime
              style={{ width: 224, marginLeft: 8, marginRight: 24 }}
              onChange={this.dateChange}
            />
            <Search
              placeholder="数据源名称、管理员姓名"
              // onSearch={value => console.log(value)}
              style={{ width: 272 }}
              onSearch={this.handleSearch}
              allowClear
              onChange={this.clearChange}
            />
          </div>
        </div>
        <Table
          rowKey={record => record.dsId}
          size="middle"
          columns={columns}
          // rowKey={record => record.login.uuid}
          dataSource={dsList}
          onChange={(e, filters, sorter) =>
            this.handleTableChange(e, filters, sorter)
          }
          loading={loading}
          locale={{ emptyText: "暂无数据！" }}
          pagination={{
            defaultPageSize: 10,
            showQuickJumper: true,
            showSizeChanger: true,
            current: pageNum,
            total: totalCount,
            showTotal: total => `共有 ${total} 条`
          }}
        />
      </div>
    );
  }
}

export default DataManagement;
